<?php

namespace App\Console\Commands;

use App\Models\Books;
use App\Models\BookShelf;
use App\Services\UniPush;
use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\BooksAutoUpdate;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Mail;

class NewChapterQueue extends Command {

    protected $name = 'NewChapterQueue';//命令名称

    protected $description = '最新章节队列更新'; // 命令描述

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取scrapy 队列数据
        $bookInfo = Redis::lpop(config('cacheKey.scrapyBookUpdate'));
        //出队消费
        if (!empty($bookInfo)){

            $bookInfo = json_decode($bookInfo,true);

            Log::info('小说更新:'.json_encode($bookInfo));

            /*更新章节总数*/
            $this->updateChapterCount($bookInfo['book_id']);

            //更新小说详情缓存
            Books::updateBookCache($bookInfo['book_id']);

            /*发送通知给用户*/
            $this->pushMessage($bookInfo);


        }else{
            die('暂无数据');
        }
    }

    /**
     * 更新章节总数
     * @param int $bookId
     * @return bool
     * */
    public function updateChapterCount($bookId)
    {
        /*获取章节总数*/
        $count = Books::getChapterCountById($bookId);
        //更新章节总数
        $book = Books::find($bookId);
        $book->chapter_count = $count;
        $book->save();
        return true;
    }

    /**
     * 发送通知
     * @param array $bookInfo
     * @return mixed
     * */
    public function pushMessage($bookInfo)
    {
        $igt = new UniPush();
        $title = '《'.$bookInfo['book_name'].'》更新啦~';
        $content = $bookInfo['new_chapter'];
        $userList = BookShelf::getUserListByBookId($bookInfo['book_id']);
//        $igt->pushMessageToList($title,$content,UniPush::NOTIFICATION_TEMPLATE,$userList);
        $igt->pushMessageToAll($title,$content,UniPush::NOTIFICATION_TEMPLATE);
        return true;
    }

}